package com.holfeld.teresa.vocabtrainer.card;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TableLayout;

import com.holfeld.teresa.vocabtrainer.R;

/**
 * @author Teresa Holfeld, teresa.holfeld@gmail.com
 */
public class ProgressView extends LinearLayout {

    private Context mContext;

    private int mNone;
    private int mLongTerm;
    private int mShortTerm;

    public ProgressView(Context context, int total) {
        super(context);
        mContext = context;
        init(null);
    }

    public ProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init(attrs);
    }

    public ProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init(attrs);
    }

    /**
     * Sets the parameter for the progress statistics. Re-draws the view.
     *
     * @param longTerm number of vocables in long term memory
     * @param shortTerm number of vocables in short term memory
     * @param none number of vocables not learned yet
     */
    public void setStatistics(int longTerm, int shortTerm, int none) {
        mLongTerm = longTerm;
        mShortTerm = shortTerm;
        mNone = none;
        initLayout();
        invalidate();
    }

    private void init(AttributeSet attrs) {
        TypedArray a = mContext.getTheme()
                .obtainStyledAttributes(attrs, R.styleable.Progress, 0, 0);
        try {
            mLongTerm = a.getInteger(R.styleable.Progress_longTerm, 0);
            mShortTerm = a.getInteger(R.styleable.Progress_shortTerm, 0);
            mNone = a.getInteger(R.styleable.Progress_none, 0);
        } finally {
            a.recycle();
        }
        initLayout();
    }

    private void initLayout() {
        setOrientation(LinearLayout.HORIZONTAL);

        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.progress_view, this, true);

        View longTerm = getChildAt(0);
        View shortTerm = getChildAt(1);
        View none = getChildAt(2);

        float sum = mLongTerm + mShortTerm + mNone;
        setWeightSum(sum);
        setWeight(longTerm, (float) mLongTerm);
        setWeight(shortTerm, (float) mShortTerm);
        setWeight(none, (float) mNone);
    }

    private void setWeight(View view, float weight) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
                LayoutParams.MATCH_PARENT);
        params.weight = weight;
        view.setLayoutParams(params);
    }
}
